package com.it.smn.divide.registrar;

import com.it.smn.divide.annotation.EnableDynamicDataSource;
import com.it.smn.divide.datasource.DynamicDataSourceRouter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author sunmannian
 * @ClassName com.it.smn.divide.registrar.DynamicDataSourceRegistrar
 * @Date 2020/8/27 17:10
 * @Version V1.0
 * Description  <向Spring中注册DynamicDataSourceRouter的Bean定义>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/8/27
 */
public class DynamicDataSourceRegistrar implements ImportBeanDefinitionRegistrar {

    public static String BEAN_NAME = "dynamicDataSourceRouter";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annotationAttributes = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(EnableDynamicDataSource.class.getName()));
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DynamicDataSourceRouter.class);
        beanDefinitionBuilder.setScope(BeanDefinition.SCOPE_SINGLETON);
        annotationAttributes.forEach((k, v) -> beanDefinitionBuilder.addPropertyValue(k, v));
        registry.registerBeanDefinition(BEAN_NAME, beanDefinitionBuilder.getBeanDefinition());
    }

}
